/**
 * 
 */
package com.rw.rule.load;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rw.database.WeightDataSource;
import com.rw.rule.LoadRule;

/**
 * 权重数据源规则,根据权重，讲数据放入一个数据集合中，通过随机获取集合中的一个数据源
 * 
 * @author lkclkc88(lkclkc88@sina.com)
 * @Date 2016年1月29日
 */
public class WeightDataSourceRule implements LoadRule {

	private static Logger log = LoggerFactory
			.getLogger(WeightDataSourceRule.class);

	private DataSource[] dataSources;

	private int maxIndex;

	private Random random;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.rw.rule.DataSourceRule#process(java.util.List)
	 */
	@Override
	public DataSource process(List<DataSource> list) {
		return dataSources[random.nextInt(maxIndex)];
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.rw.rule.DataSourceRule#init(java.util.List)
	 */
	@Override
	public void initRule(List<DataSource> list) {
		if (null == list || list.size() == 0) {
			if (log.isWarnEnabled()) {
				log.warn("*******  salves dataSource is null ******");
			}
			return;
		} else {
			List<DataSource> dataSources = new LinkedList<DataSource>();
			for (DataSource dataSource : list) {
				int weight = 0;
				if (dataSource instanceof WeightDataSource) {
					WeightDataSource weightDataSource = (WeightDataSource) dataSource;
					weight = weightDataSource.getWeight();

				}
				if (weight <= 1) {
					weight = 1;
				}
				if (weight > 100) {
					weight = 100;
				}
				for (int i = 0; i < weight; i++) {
					dataSources.add(dataSource);
				}
			}
			this.dataSources = dataSources.toArray(new DataSource[dataSources
					.size()]);
			maxIndex = dataSources.size() - 1;
			this.random = new Random();
		}
	}

}
